package files

import (
	"log"
	"strings"

	"gitee.com/xuender/oils/logs"
	"github.com/spf13/cobra"
)

// Context 上下文.
type Context struct {
	// DataBasePath 数据库目录.
	DataBasePath string
	Limit        int
	Offset       int
	Ext          string
	// Simple 简单输出格式.
	Simple    bool
	Debug     bool
	Remove    bool
	Order     string
	Desc      bool
	Regexp    bool
	HasRegexp bool
}

// NewContext 新建上下文.
func NewContext(cmd *cobra.Command) *Context {
	ctx := &Context{}

	ctx.regexp()

	if db, err := cmd.Flags().GetString("db"); db != "" && err == nil {
		ctx.DataBasePath = db
	}

	ctx.Remove, _ = cmd.Flags().GetBool("remove")
	ctx.Simple, _ = cmd.Flags().GetBool("simple")

	ctx.search(cmd)
	ctx.log(cmd)

	return ctx
}

func (p *Context) search(cmd *cobra.Command) {
	if limit, err := cmd.Flags().GetInt("limit"); err == nil {
		p.Limit = limit
	}

	if offset, err := cmd.Flags().GetInt("offset"); err == nil {
		p.Offset = offset
	}

	if order, err := cmd.Flags().GetString("order"); err == nil {
		p.Order = order
	}

	if ext, err := cmd.Flags().GetString("ext"); err == nil {
		p.Ext = ext
		if ext != "" && !strings.HasPrefix(ext, ".") {
			p.Ext = "." + p.Ext
		}
	}

	p.Regexp, _ = cmd.Flags().GetBool("regexp")
	p.Desc, _ = cmd.Flags().GetBool("desc")
}

func (p *Context) log(cmd *cobra.Command) {
	logs.SetLevel(logs.LevelInfo)

	if d, err := cmd.Flags().GetBool("debug"); err == nil && d {
		p.Debug = d

		logs.SetLevel(logs.LevelDebug)
		logs.SetFlags(log.Lshortfile | log.LstdFlags)
	}
}
